package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: duolaimall
 * @description: 注册服务实现
 * @author: zhong
 * @create: 2022-08-01 11:00
 **/
@Slf4j
@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    private JavaMailSender mailSender;    //idea提示有误

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        //判空
        request.requestCheck();
        //判重
        validateRepeat(request.getUserName());
        //插入
        Member member = new Member();
        member.setUsername(request.getUserName());
        member.setEmail(request.getEmail());
        String userPwd = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        log.info("密码密文:{}",userPwd);
        member.setPassword(userPwd);
        member.setIsVerified("N");
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setState(1);
        int addRow = memberMapper.insert(member);
        if (addRow != 1) {
            log.info("无法新增至数据库");
            userRegisterResponse.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
            userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
            return userRegisterResponse;
        }
        UserVerify newUser = new UserVerify();
        String key = member.getEmail() + member.getUsername() + UUID.randomUUID().toString();
        String uuId = DigestUtils.md5DigestAsHex(key.getBytes());
        newUser.setUuid(uuId);
        newUser.setRegisterDate(new Date());
        newUser.setIsVerify("N");
        newUser.setIsExpire("N");
        newUser.setUsername(member.getUsername());
        int addVerifyRow = userVerifyMapper.insert(newUser);
        if (addVerifyRow != 1) {
            userRegisterResponse.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
            return userRegisterResponse;
        }
        sendEmail(uuId,member.getEmail(),member.getUsername());
        log.info("用户名:{},密码:{}邮箱待验证", request.getUserName(), request.getUserPwd());
        userRegisterResponse.setCode(UserRetCode.SUCCESS.getCode());
        userRegisterResponse.setMsg(UserRetCode.SUCCESS.getMessage());
        return userRegisterResponse;
    }

    @Override
    public UserVerifyResponse verify(UserVerifyRequest request) {
        request.requestCheck();
        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();
        //isExpired?
        UserVerify userVerify = new UserVerify();
        userVerify.setUuid(request.getUuid());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        UserVerify target = userVerifyMapper.selectOne(userVerify);
        if (target == null) {
            log.info("uuid不合法，伪造的访问链接|已超时的链接|已验证的链接");
            userVerifyResponse.setCode(UserRetCode.USERVERIFY_INFOR_INVALID.getCode());
            userVerifyResponse.setMsg(UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
            return userVerifyResponse;
        }
        long registerDate = target.getRegisterDate().getTime();
        long currentDate = new Date().getTime();
        long expiredTime = 1000*60*5;//5min过期
        if (currentDate - registerDate > expiredTime) {
            log.info("注册链接超时失效");
            target.setIsExpire("Y");
            userVerifyMapper.updateByPrimaryKeySelective(target);
            userVerifyResponse.setCode(UserRetCode.USERVERIFY_INFOR_INVALID.getCode());
            userVerifyResponse.setMsg(UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
            return userVerifyResponse;
        }
        //update isVerified & member
        Member verified = new Member();
        verified.setIsVerified("Y");
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", request.getUserName());
        int updateRow = memberMapper.updateByExampleSelective(verified, example);
        if (updateRow != 1) {
            log.info("注册验证失败");
            userVerifyResponse.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            userVerifyResponse.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
            return userVerifyResponse;
        }
        target.setIsVerify("Y");
        target.setIsExpire("Y");
        userVerifyMapper.updateByPrimaryKeySelective(target);
        log.info("注册验证生效");
        userVerifyResponse.setCode(UserRetCode.SUCCESS.getCode());
        userVerifyResponse.setMsg(UserRetCode.SUCCESS.getMessage());
        return userVerifyResponse;
    }

    private void sendEmail(String uuId,String email,String userName) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("别码了-CS-MALL用户激活");
        message.setFrom("13081856640@163.com");
        message.setTo(email);
        StringBuilder text = new StringBuilder("点击超链接以完成注册：\r\n");
        String hyperLink = "http://localhost:8101/user/verify?";
        text.append(hyperLink).append("uuId=").append(uuId).append("&userName=").append(userName);
        message.setText(text.toString());
        mailSender.send(message);
    }

    private void validateRepeat(String userName) {
        Member member = new Member();
        member.setUsername(userName);
        List<Member> members = memberMapper.select(member);
        if (!members.isEmpty()) {
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(), UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());        }
    }


}
